/**
 * Copyright 2015 Qiyi Inc. All rights reserved.
 *
 * @file:   Carousel.Grid.js
 * @author: karkarrotxu@qiyi.com
 * @date:   2016-05-30
 */
qui(
    function (require, exports, module) {
        Carousel.Grid = function (options) {
            this.dao = Carousel.Dao;
            this.config = Carousel.Config;
            this.task = Carousel.Task;
            this.options = options || {};
        };
        Com.inherits(Carousel.Grid, Ancestor.Grid).extend({
            //--------CarouselEdit start==========/
            runDayList: function () {
                var self = this;
                self.dayListUseDlg();
                $("button[name=btn_automation_rule]").hide();
                $("button[name=btn_auto_rule]").hide();
                $("button[name=btn_automation_library]").hide();

                self.$grid = self.options.$grid
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getContentTypeTask(self.dao.cfgName.ContentType));
                taskArr.push(self.task.getLogType(self.dao.cfgName.LogType));
          //      taskArr.push(self.task.getAdDuration(self.dao.cfgName.Ad_duration));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startDayList();
                    self.initAdvertDialog();
                });
                EpgWeb.ajaxQueue.startLoad();
            },

            startDayList: function (options, callback) {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                switch (channelData.automation) {
                    case 1:
                        $("button[name=btn_automation_rule]").show();
                        break;
                    case 0:
                        $("button[name=btn_auto_rule]").show();
                        break;
                    case 2:
                        $("button[name=btn_automation_library]").show();
                        break;
                }
                self.initDayList();
                self.bindListBasicEvent()
                self.initWeekToolBar();
                self.initAdvertDialog();
            },
            initDayList: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST);
                self.$grid.jqGrid(gridConfig);
                self.bindDayTListEvent();
            },
            bindDayTListEvent: function () {
                var self = this;
                $("<span style='color:#187ddb'>直播视频只能回看二天！</span>").appendTo($("#t_list"));
                var bdiv = $(".ui-jqgrid-bdiv");

                $("<label style='width: 40px;float:right;'>PM</label>").bind("click", function () {
                    if (bdiv[0].scrollHeight <= bdiv[0].clientHeight) {
                        return;
                    }
                    var allDate = self.$grid.jqGrid("getRowData");
                    var checkPM = "";
                    var interrupt = 0;
                    for (var i = 0; i < allDate.length; i++) {
                        checkPM = allDate[i].startPlayTime.substr(11);
                        if (checkPM >= "12:00:00") {
                            interrupt = i;
                            break;
                        }
                    }
                    bdiv.scrollTop(interrupt / allDate.length * bdiv[0].scrollHeight)
                }).appendTo($("#t_list"));
                $("<label style='width: 40px;float:right;'>AM</label>").bind("click", function () {
                    bdiv.scrollTop(0)
                }).appendTo($("#t_list"));
                self.$grid.jqGrid('navGrid', "#pager", { edit: false, add: false, del: false, search: false, refresh: false});
                self.$grid.jqGrid('navButtonAdd', "#pager", {caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        console.log("self del");
                        var gridElement = self.$grid;
                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        })
                        if (ids.length == 0) {
                            return
                        }
                        self.dao.programBatchDel({ids: "[" + ids.join(",") + "]", dateTime: self.config.dateTime, channelId: self.dao.channelId}, function (data) {
                            Carousel.Util.reloadHandler(data);
                        });
                    }, position: "last", title: "批量删除", cursor: "pointer"});
            },


            bindListBasicEvent: function () {
                var self = this;
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
                $("button[name=btn_auto_sort]").bind("click", function (event) {
                    console.log("wait to deal");
                    $("button[name=btn_auto_sort]").attr("disabled","disabled")
                    var selectedId = self.$grid.jqGrid("getGridParam", "selrow")
                    console.log(" selectedId " + selectedId);
                    var selectedData = self.$grid.jqGrid('getRowData', selectedId);
                    console.log("selectedData:" + JSON.stringify(selectedData));
                    self.dao.gridSort({fatherId: self.dao.channelId, sortDate: self.config.dateTime + " 00:00:00"}, function (data) {
                        $("button[name=btn_auto_sort]").removeAttr("disabled");
                        Carousel.Util.reloadHandler(data);
                    });
                })
                $("button[name=btn_insert]").bind("click", function (event) {
                    var selectedId = self.$grid.jqGrid("getGridParam", "selrow")
                    var toHref = "/epg/carousel_insert.html?fatherId=" + self.dao.channelId;
                    console.log(" selectedId " + selectedId);
                    var currentDay = EpgWeb.Util.formatDateTimeFormat(new Date())
                    var startTime = null;
                    if (selectedId != null) {
                        var selectedData = self.$grid.jqGrid('getRowData', selectedId);
                        startTime = selectedData.endPlayTime;
                        if (selectedData.endPlayTime.substr(0, 10) > selectedData.startPlayTime.substr(0, 10)) {
                            EpgWeb.Plugin.showTips({content: "不能选择跨天节目的结束时间!", type: "error"})
                            return
                        }
                    } else {
                        startTime = self.config.dateTime + " 00:00:00";
                    }
                    if (currentDay.substr(0, 10) > startTime.substr(0, 10)) {
                        EpgWeb.Plugin.showTips({content: "插入天数不能小于操作天数", type: "error"})
                        return;
                    }
                    toHref += "&startTime=" + startTime;
                    Carousel.Util.openNewHtml(toHref);
                })
                $("button[name=btn_auto_rule]").bind("click", function (event) {
                    Carousel.Util.openNewHtml("/epg/carousel_rule.html?fatherId=" + self.dao.channelId);
                })
                $("button[name=btn_automation_rule]").bind("click", function (event) {
                    Carousel.Util.openNewHtml("/epg/carousel_automation_rule.html?fatherId=" + self.dao.channelId);
                });
                $("button[name=btn_automation_library]").bind("click", function (event) {
                    Carousel.Util.openNewHtml("/epg/carousel_automation_library.html?fatherId=" + self.dao.channelId);
                });
                self.dao.doAuthData({
                    url: '/epg/config_manager.html',
                    doSuccess: function () {
                        $("button[name=btn_search_config]").show();
                        $("button[name=btn_search_config]").bind("click", function (event) {
                            Carousel.Util.openNewHtml("/epg/config_manager.html?id=" + self.dao.channelId);
                        });
                    }
                })
            },


            getListParam: function () {
                var self = this;
                return  {startDate: Carousel.Config.dateTime + " 00:00:00", endDate: Carousel.Config.dateTime + " 23:59:59", fatherId: self.dao.channelId, pageSize: 40}
            },

            //--------CarouselEdit End==========/
            //--------CarouselInsert  start==========/
            runInsertList: function () {
                var self = this;
                self.insertUseDlg();
                var startTime = Com.url.getParameter("startTime")
                if (startTime == null) {
                    EpgWeb.Plugin.showTips({content: "参数异常", type: "error"})
                    return;
                }
                self.$grid1 = self.options.$gridType1;
                self.$grid2 = self.options.$gridType2;
                var taskArr = [];
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                taskArr.push(self.task.platSettingsTask(self.dao.cfgName.platSettings, {channelId: self.dao.channelId}));
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.platformsTask(self.dao.cfgName.PlayPlatform))
                taskArr.push(self.task.getPlatformReferTask(self.dao.cfgName.PlatformRefer));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startInsertList();
                });
                Carousel.Config.dateTime = EpgWeb.Util.formatDateTimeFormat(new Date(startTime.replace(/-/g, "/")))
                EpgWeb.ajaxQueue.startLoad();
            },
            startInsertList: function () {
                var self = this;
                self.initListAddType1Grid();
                self.initListAddType2Grid();
                self.bindInsertEvent();
            },
            initListAddType1Grid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST_ADD_TYPE1);
                self.$grid1.jqGrid(gridConfig);
            },
            initListAddType2Grid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIST_ADD_TYPE2);
                self.$grid2.jqGrid(gridConfig);
            },
            bindInsertEvent: function () {
                var self = this;
                var parent = $("#addProgramView");
                parent.find("button[name=queryProgram]").bind("click", function (event) {
                    self.queryProgram();
                });
                parent.find("button[name=btn_addType1]").bind("click", function (event) {
                    self.batchInsertLegoProgram("listAdd1");
                });
                parent.find("button[name=btn_addType2]").bind("click", function (event) {
                    self.batchInsertLiveProgram("listAdd2")
                });
                parent.find("button[name=btn_addType3]").bind("click", function (event) {
                    self.batchInsertCarouselLibrary("listAdd1");
                });


                Carousel.Util.bindDate("minDateTime", "maxDateTime");
                parent.find("button[name=btn_addType3]").hide();
                var channelData = self.dao.getChannel();
                if( 2 == channelData.automation  ){
                    parent.find("button[name=btn_addType3]").show();
                }

                var selectTarget = $("#addProgramView").find("select[name=insertType]");
                selectTarget.bind("change", function (event) {
                    var typeMode = selectTarget.val();
                    $("#addType1").hide();
                    $("#addType1").clearGridData();
                    $("#addType2").hide();
                    $("#addType2").clearGridData();
                    if (typeMode == "type1") {
                        $("#addType1").show();
                        $("#dateTimeDiv").hide();
                        $("#div_new_type1").show();
                        $("#videoOrderDiv").show();
                        $("#div_albumName_typ1").show();
                        $("#div_tags_typ1").show();
                        $("input[type=text]").val("");
                    } else {
                        $("#addType2").show();
                        $("#dateTimeDiv").show();
                        $("#div_new_type1").hide();
                        $("#videoOrderDiv").hide();
                        $("#div_albumName_typ1").hide();
                        $("#div_tags_typ1").hide();
                        $("input[type=text]").val("");
                    }
                    $("input[name=minTime]").val(60);
                })
                selectTarget.change();
            },

            batchInsertLegoProgram: function (tableId) {
                var self = this;
                var gridElement = $("#" + tableId);
                var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                var ids = [];
                $.each(selectedtrArr, function (i, element) {
                    ids.push(parseInt($(element).attr("id")));
                })
                if (ids.length == 0) {
                    return;
                }
                // doSort ;
                ids = self.doSort(ids);
                Carousel.Util.addDisAble();
                Carousel.Config.saveIds = ids;
                self.checkMulti();
                console.log("ids " + JSON.stringify(ids));
            },

            checkMulti: function () {
                var self = this;
                var lDateFormat = self.config.dateTime.substr(0, 10);
                var sendData = {startDate: lDateFormat + " 00:00:00", endDate: lDateFormat + " 23:59:59", fatherId: self.dao.channelId, pageSize: 2000}
                self.dao.getProgramList(sendData, function (rdata) {
                    if (rdata != null) {
                        Carousel.Util.checkMultiCallBack(rdata.data,"batchAdd");
                    } else {
                        console.log("getProgramListTask fail");
                    }
                })
            },
            checkLibraryMulti:function(){
                var self = this;
                var sendData = {channelId: self.dao.channelId, pageSize: 2000}
                self.dao.getCarouselEpisodeList (sendData, function (rdata) {
                    if (rdata != null) {
                        if( rdata.code != "A00000"){
                            SystemDialog.queryAlert(rdata.msg);
                            return ;
                        }
                        $.each(rdata.data.result,function(i,element){
                            element.carouselEpisode = element.qipuId;
                        })
                        Carousel.Util.checkMultiCallBack(rdata.data,"episodeBatchAdd");
                    } else {
                        console.log("checkLibraryMulti fail");
                    }
                })
            },

            doSort: function (ids) {
                var self = this;
                var responseData = self.dao.getFromCache("gridData1");
                var dataArr = responseData != null ? responseData.rows : [];
                var sortArr = [];
                $.each(dataArr, function (i, element) {
                    if (ids.indexOf(element.qipuId) != -1) {
                        sortArr.push(element);
                    }
                });
                sortArr.sort(function (a, b) {
                    if (a.videoOrder != b.videoOrder) {
                        return a.videoOrder > b.videoOrder;
                    }
                    return a.globalPublishDate > b.globalPublishDate;
                });
                var afterSort = [];
                $.each(sortArr, function (i, element) {
                    afterSort.push(element.qipuId);
                })
                console.log("ids " + JSON.stringify(ids) + " afterSort:" + JSON.stringify(afterSort));
                return afterSort;
            },


            queryProgram: function () {
                var self = this;
                var queryObject = {};
                var parent = $("#addProgramView");
                var isLiveType = parent.find("select[name=insertType]").val() == "type2";
                var queryName = jfUtil.simplized($.trim(parent.find("input[name=queryName]").val()));
                var queryQipuId = $.trim(parent.find("input[name=qipuId]").val());
                queryObject.queryName = queryName;
                queryObject.queryQipuId = queryQipuId;
                queryObject.minTime = parent.find("input[name=minTime]").val();
                queryObject.maxTime = parent.find("input[name=maxTime]").val();
                queryObject.isLive = isLiveType;
                queryObject.startDate = parent.find("input[name=minDateTime]").val();
                queryObject.endDate = parent.find("input[name=maxDateTime]").val();
                queryObject.minVideoOrder = parent.find("input[name=minVideoOrder]").val();
                queryObject.maxVideoOrder = parent.find("input[name=maxVideoOrder]").val();
                queryObject.albumName = $.trim(parent.find("input[name=albumName]").val());
                var channelObj = $($("select[name=channel]").children()[$("select[name=channel]")[0].selectedIndex]);
                var contentTypeObj = $($("select[name=contentType]").children()[$("select[name=contentType]")[0].selectedIndex]);
                queryObject.kvPair = [];
                queryObject.kvPair.push({value: channelObj.val(), name: "filter_EQL_channel"});
                queryObject.kvPair.push({value: contentTypeObj.val(), name: contentTypeObj.attr("name") });
                queryObject.customTags = parent.find("input[name=customTags]").val();
                self.queryInsert(queryObject)
            },

            queryInsert: function (sendObject) {
                var self = this;
                var checkArr = [];
                checkArr.push({value: sendObject.minTime, error: "最小时长需要数字格式", type: "positive"});
                checkArr.push({value: sendObject.minTime, error: "最小时长不能小于60秒", type: "ge", other: 60});
                if (sendObject.maxTime.length > 0) {
                    checkArr.push({value: sendObject.maxTime, error: "最大时长需要数字格式", type: "positive"});
                    checkArr.push({value: parseInt(sendObject.maxTime), error: "最小时长不能大于最大时长", type: "ge", other: parseInt(sendObject.minTime) });
                }
                if (sendObject.queryQipuId.length > 0) {
                    checkArr.push({value: sendObject.queryQipuId, error: "qipuId需要数字格式", type: "positive"});
                }

                if (!sendObject.isLive) {
                    if (sendObject.minVideoOrder.length > 0) {
                        checkArr.push({value: sendObject.minVideoOrder, error: "最小集数需非负整数", type: "number"});
                    }
                    if (sendObject.maxVideoOrder.length > 0) {
                        checkArr.push({value: sendObject.maxVideoOrder, error: "最大集数需要非负整数", type: "number"});
                    }
                    if (sendObject.minVideoOrder.length > 0 && sendObject.maxVideoOrder.length > 0) {
                        checkArr.push({value: parseInt(sendObject.maxVideoOrder), error: "终止集数必须大于等于开始集数", type: "ge", other: parseInt(sendObject.minVideoOrder) });
                    }
                    if (sendObject.customTags.length > 0) {
                        sendObject.customTags = sendObject.customTags.replace(/，/g, ",");
                    }
                    if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                        console.log("interrupt queryInsert")
                        return false;
                    }
                }

                if (!EpgWeb.Plugin.Validate.batchCheck(checkArr)) {
                    console.log("interrupt queryInsert")
                    return false;
                }
                if (sendObject.isLive) {
                    self.fillGridType2(sendObject);
                } else {
                    var task = self.task.platSettingsTask(self.dao.cfgName.platSettings, {channelId: self.dao.channelId});
                    EpgWeb.ajaxQueue.removeTask(task.regName);
                    EpgWeb.ajaxQueue.push(task.regName, task.options);
                    EpgWeb.ajaxQueue.afterLoadComplete(function () {
                        self.fillGridType1(sendObject);
                    });
                    EpgWeb.ajaxQueue.startLoad();
                }
            },

            batchInsertLiveProgram: function (tableId) {

                var gridElement = $("#" + tableId);
                var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                var ids = [];
                $.each(selectedtrArr, function (i, element) {
                    ids.push(parseInt($(element).attr("id")));
                })
                if (ids.length == 0) {
                    return;
                }
                Carousel.Util.addDisAble();
                Carousel.Config.saveIds = ids;
                Carousel.Config.invalidArr = [];
                Carousel.Util.batchAdd();
                console.log("ids " + JSON.stringify(ids));
            },

            batchInsertCarouselLibrary: function (tableId) {
                var gridElement = $("#" + tableId);
                var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                var ids = [];
                var self = this;
                $.each(selectedtrArr, function (i, element) {
                    ids.push(parseInt($(element).attr("id")));
                })
                if (ids.length == 0) {
                    return;
                }
                Carousel.Util.addDisAble();
                Carousel.Config.saveIds = ids;
                Carousel.Config.invalidArr = [];
                self.checkLibraryMulti();
                console.log("ids " + JSON.stringify(ids));
            },

            fillGridType1: function (sendObj) {
                var self = this;
                self.$grid1.clearGridData();
                var paramsData = Carousel.Util.getSearchParamsBySettings();
                //append base
                paramsData["filter_GTL_qipuId"] = 0;
                paramsData["t"] = 0;
                //page params
                paramsData["page.pageNo"] = 1;
                paramsData["page.order"] = "desc";
                paramsData["page.orderBy"] = "createTime";
                paramsData["page.pageSize"] = 30;

                if (sendObj.queryName.length > 0) {
                    paramsData["filter_LIKES_displayName"] = sendObj.queryName
                }
                if (sendObj.queryQipuId.length > 0) {
                    paramsData["filter_EQL_qipuId"] = sendObj.queryQipuId;
                }
                if (sendObj.minTime.length > 0) {
                    paramsData["filter_GEL_duration"] = parseInt(sendObj.minTime) * 1000;
                }
                if (sendObj.maxTime.length > 0) {
                    paramsData["filter_LEL_duration"] = parseInt(sendObj.maxTime) * 1000;
                }

                if (sendObj.minVideoOrder.length > 0) {
                    paramsData["filter_GEL_videoOrder"] = parseInt(sendObj.minVideoOrder);
                }
                if (sendObj.maxVideoOrder.length > 0) {
                    paramsData["filter_LEL_videoOrder"] = parseInt(sendObj.maxVideoOrder);
                }
                if (sendObj.albumName.length > 0) {
                    paramsData["filter_LIKES_albumDisplayName"] = sendObj.albumName;
                }
                if (sendObj.customTags.length > 0) {
                    paramsData["filter_INS_customTags"] = sendObj.customTags;
                }
                $.each(sendObj.kvPair, function (i, element) {
                    if (element.value.length > 0) {
                        paramsData[element.name] = element.value;
                    }
                })

                var requestData = {url: EpgWeb.Constant.thirdUrl_apis_search_area_url, type: "get", params: paramsData, needCookie: true};
                var parentView = $("#addProgramView");
                parentView.find("button[name=queryProgram]").attr("disable", "disabled");

                self.$grid1.setGridParam({page: 1, url: EpgWeb.urlConfig.redirect, loadtext: '加载中...', pageSize: 50,
                    datatype: "json",
                    loadui: "block", postData: {"request": JSON.stringify(requestData), timeSign: Date.now()}}).trigger("reloadGrid");

            },

            fillGridType2: function (sendObj) {
                var self = this;
                self.$grid2.clearGridData();
                var sendData = {startDate: "", endDate: ""};
                if (sendObj.endDate.length > 0) {
                    if (!EpgWeb.Plugin.Validate.checkDateFormat(sendObj.endDate)) {
                        EpgWeb.Plugin.showTips({content: "最大开始时间格式错误"})
                        return;
                    }
                    sendData.endDate = sendObj.endDate;
                }

                if (sendObj.startDate.length > 0) {
                    if (!EpgWeb.Plugin.Validate.checkDateFormat(sendObj.startDate)) {
                        EpgWeb.Plugin.showTips({content: "最小开始时间格式错误"})
                        return;
                    }
                    sendData.startDate = sendObj.startDate;
                } else {
                    var defaultDate = new Date();
                    sendData.startDate = Carousel.Util.quickDateFormat(defaultDate);
                    if (sendData.endDate.length > 0) {
                        if (sendData.startDate > sendData.endDate) {
                            sendData.startDate = "";
                        }
                    } else {
                        if (sendData.startDate < Carousel.Config.dateTime) {
                            sendData.startDate = Carousel.Config.dateTime;
                        }
                    }
                }
                sendData.pageSize = 50;
                sendData.qipuId = '';
                sendData.pname = '';
                sendData.maxTime = '';
                if (sendObj.queryQipuId.length > 0) {
                    sendData.qipuId = sendObj.queryQipuId;
                }
                if (sendObj.queryName.length > 0) {
                    sendData.pname = $.trim(sendObj.queryName);
                }
                sendData.minTime = sendObj.minTime;
                if (sendObj.maxTime.length > 0) {
                    sendData.maxTime = sendObj.maxTime;
                }

                $(".norecords").hide()
                self.$grid2.setGridParam({url: EpgWeb.urlConfig.programLiveQueryUrl, loadtext: '加载中...', page: 1,
                    datatype: "json",
                    loadui: "block", postData: sendData}).trigger("reloadGrid");
            },

            //--------CarouselInsert  end==========/


            //--------carousel automation library  start==========/
            runLibrary: function () {
                var self = this;
                self.libraryUseDlg();
                $("button[name=btn_automation_rule]").hide();
                $("button[name=btn_auto_rule]").hide();
                $("button[name=btn_automation_library]").hide();

                self.$grid = self.options.$grid
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramTypeTask(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getContentTypeTask(self.dao.cfgName.ContentType));
                var fatherId = Com.url.getParameter("fatherId");
                if (EpgWeb.Plugin.Validate.checkNum(fatherId)) {
                    self.dao.channelId = Number(fatherId);
                    taskArr.push(self.task.getChannel(self.dao.cfgName.getChannel, {id: self.dao.channelId}));
                }
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    Carousel.Config.IS_RULE_RUNNING = true;
                    Carousel.Util.queryVirtualRule({channelId:self.dao.channelId},function(flag){
                        if(flag){
                            self.startLibrary();
                        }
                    } );
                });
                EpgWeb.ajaxQueue.startLoad();
            },

            startLibrary: function () {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                self.initLibrary();
                self.bindLibraryBasicEvent();
            },
            initLibrary: function (options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_LIBRARY);
                self.$grid.jqGrid(gridConfig);
                self.$grid.setGridParam({page: 1, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: self.getLibraryParam()}).trigger("reloadGrid");

            },
            getLibraryParam: function () {
                var self = this;
                return  {channelId: self.dao.channelId};
            },
            bindLibraryBasicEvent: function () {
                var self = this;
                $("button[name=btn_insert]").bind("click", function (event) {
                    var toHref = "/epg/carousel_insert.html?fatherId=" + self.dao.channelId;
                    var currentDay = EpgWeb.Util.formatDateTimeFormat(new Date())
                    toHref += "&startTime=" + currentDay.substr(0, 10) + " 00:00:00";
                    Carousel.Util.openNewHtml(toHref);
                });

                $("button[name=btn_rule_start]").bind("click", function (event) {
                    Carousel.Util. queryVirtualRule( {channelId: self.dao.channelId} ,function(flag){
                        if(flag ){
                            if(!Carousel.Util.IS_RULE_RUNNING){
                                Carousel.Util.notifyRuleChangeStatus(Carousel.Config.ChangeStatus.STATUS_PROGRAM_RUN);
                            }
                        }
                    } );
                })
                $("button[name=btn_rule_stop]").bind("click", function (event) {

                    Carousel.Util.queryVirtualRule( {channelId: self.dao.channelId} ,function(flag){
                        if(flag ){
                            if(Carousel.Config.IS_RULE_RUNNING){
                                var msg = Carousel.Config.Hint.STOP_RULE_HINT;
                                SystemDialog.queryConfirm(msg, function (flag) {
                                    if (flag === true) {
                                        Carousel.Util.notifyRuleChangeStatus(Carousel.Config.ChangeStatus.STATUS_PROGRAM_IDLE)
                                    }
                                })
                            }
                        }
                    } );
                })

                self.$grid.jqGrid('navGrid', "#pager", {
                    edit: false,
                    add: false,
                    del: false,
                    search: false,
                    refresh: false
                });
                self.$grid.jqGrid('navButtonAdd', "#pager", {
                    caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        if (Carousel.Config.IS_RULE_RUNNING) {
                            SystemDialog.queryAlert("规则执行中不能删除");
                            return;
                        }
                        var gridElement = $("#list");
                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        });

                        if (ids.length == 0) {
                            return;
                        }

                        Carousel.Util.episodeBatchDel(ids.join(","), self.dao.channelId);
                    }, position: "last", title: "批量删除", cursor: "pointer"
                });
            },
            //--------carousel automation library  end==========/


            //====================carouselRule start========================================/
            runRule: function () {
                var self = this;
                self.$grid = self.options.$grid;
                self.model = self.options.model;
                var taskArr = [];
                taskArr.push(self.task.getLiveProgramType(self.dao.cfgName.liveProgramType));
                taskArr.push(self.task.getLiveChannelType(self.dao.cfgName.liveChannelType));
                taskArr.push(self.task.getLiveType(self.dao.cfgName.LiveType));
                taskArr.push(self.task.getGradeType(self.dao.cfgName.episodeGradeType));
                $.each(taskArr, function (index, element) {
                    EpgWeb.ajaxQueue.push(element.regName, element.options);
                })
                EpgWeb.ajaxQueue.afterLoadComplete(function () {
                    self.startRule();
                })
                EpgWeb.ajaxQueue.startLoad();
            },

            startRule: function () {
                var self = this;
                var channelData = self.dao.getChannel();
                if (!Carousel.Util.isCarouselCheck(channelData)) {
                    return;
                }
                self.initRuleGrid();
                self.bindBasicRuleEvent();
            },
            initRuleGrid: function () {
                var self = this;
                var gridConfig = self.getGridConfig(self.config.TABLE_RUN);
                self.$grid.jqGrid(gridConfig);
                self.$grid.setGridParam({page: 1, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: {fatherId: self.dao.channelId}}).trigger("reloadGrid");
            },

            bindBasicRuleEvent: function () {
                var self = this;
                self.$grid.jqGrid('navGrid', "#pager", {
                    edit: false,
                    add: false,
                    del: false,
                    search: false,
                    refresh: false
                });
                self.$grid.jqGrid('navButtonAdd', "#pager", {
                    caption: "批量删除", buttonicon: "ui-icon ui-icon-trash",
                    onClickButton: function () {
                        var gridElement = $("#list");
                        var dataOriginl = gridElement.jqGrid("getRowData");
                        var hiddenData = JSON.parse(dataOriginl[0].hiddenData);
                        var fatherId = hiddenData.fatherId;
                        var selectedtrArr = gridElement.find("tr[aria-selected=true]");
                        var ids = [];
                        $.each(selectedtrArr, function (i, element) {
                            ids.push(parseInt($(element).attr("id")));
                        });
                        if (ids.length == 0) {
                            return;
                        }
                        // Carousel.Util.ruleDel()
                        //Carousel.Operation.programBatchDel(ids);
                        //   Carousel.Operation.ruleDel(ids.join(','), fatherId, "是否确认删除本页内所有已选择的过期规则？删除后不可恢复");
                    }, position: "last", title: "批量删除", cursor: "pointer"
                });
            },

            //====================carouselRule end========================================/

            //====================carouselAutomationRule start========================================/

            runAutomationRule: function () {

            },
            //====================carouselAutomationRule end========================================/


            //====================initSuggest start========================================/

            initSuggest: function () {
                var gridSelf = this;
                var albumSuggest = {
                    options: {
                        _beforeSuggest: function (callback) {
                            var task = gridSelf.task.platSettingsTask(gridSelf.dao.cfgName.platSettings, {channelId: gridSelf.dao.channelId});
                            EpgWeb.ajaxQueue.removeTask(task.regName);
                            var ajaxData = task.options;
                            self.dao.sendAjax(ajaxData.url, ajaxData.type, ajaxData.data, function (data) {
                                if (data != null && data.code == "A00000") {
                                    Carousel.ajaxManager.push(task.regName, task.options, data, false);
                                    callback.call();
                                } else {
                                    EpgWeb.Plugin.showTips({content: "发生异常", type: "error"});
                                }
                            })
                        },
                        _doSuggest: function (request, response, param) {
                            var self = this,
                                options = self.options,
                                url = options.url,
                                getParam = null,
                                term = $.trim(request.term),
                                getParam = options.getParam;
                            if (getParam) {
                                if ($.isFunction(options.getParam)) {
                                    param = $.extend(true, param, getParam.call(self, term));
                                } else if ($.isPlainObject(getParam)) {
                                    param = $.extend(true, param, getParam);
                                }
                            }
                            self._getSuggestData(url, options.method, param, $.proxy(self.options._handleResponse, self, request, response));
                        },
                        _handleResponse: function (request, response, data) {
                            var self = this,
                                options = self.options,
                                term = $.trim(request.term),
                                dataProcess = options.process,
                                ret = dataProcess.call(self, data, term);

                            ret = $.ui.autocomplete.filter(ret, term);

                            if (options.highlight) {
                                options.highlight.call(self, ret, self._displayKey, term);
                            }

                            self.result = ret;
                            if (ret.length > 0) {
                                Carousel.Util.checkQipuPlatformControl(response, ret);
                            }
                            //response
                        },
                        url: EpgWeb.urlConfig.redirect,
                        source: function (request, response) {
                            var self = this,
                                options = self.options,
                                term = $.trim(request.term),
                                url = null,
                                getParam = null,
                                param = {};
                            if (!term) {
                                return null;
                            }

                            if (!options.ignoreWord) {
                                //传递 word  term
                                param = {
                                    word: term
                                };
                            }

                            param = $.extend(true, options.otherParam, param);

                            if ($.isFunction(self.options._beforeSuggest)) {
                                self.options._beforeSuggest.call(self, function () {
                                    self.options._doSuggest.call(self, request, response, param)
                                })
                            } else {
                                self.options._doSuggest.call(self, request, response, param)
                            }
                        },
                        method: "post",
                        multiple: false,
                        parseValue: function () {
                            var val = this.element.val(),
                                ret = []
                            return ret;
                        },
                        select: function (event, object) {
                            var msg = [];
                            var self = this;
                            if (object.item.hintMsgObj.missPPSClient) {
                                msg.push(Carousel.ErrorMsg.PPS_CLIENT_MSG);
                            }
                            if (object.item.hintMsgObj.missQIYIClient) {
                                msg.push(Carousel.ErrorMsg.QIYI_CLIENT_MSG);
                            }
                            if (object.item.hintMsgObj.missPPSRegion) {
                                msg.push(Carousel.ErrorMsg.PPS_REGION_MSG);
                            }
                            if (object.item.hintMsgObj.missQIYIRegion) {
                                msg.push(Carousel.ErrorMsg.QIYI_REGION_MSG);
                            }

                            self.value = "";
                            if (msg.length > 0) {
                                SystemDialog.queryConfirm(msg.join("<br>"), function (flag) {
                                    if (flag === true) {
                                        self.value = object.item.id + "";
                                        gridSelf.fillRuleView(object.item)
                                    }
                                });
                            } else {
                                self.value = object.item.id + "";
                                gridSelf.fillRuleView(object.item)
                            }
                            return false;
                        },
                        getParam: function (term) {
                            var currentTime = new Date().getTime();
                            var params = Carousel.Util.getSearchParamsBySettings();
                            params["word"] = term;
                            params["size"] = 20;
                            params["type"] = "displayName";
                            var requestData = {url: Carousel.Constant.thirdUrl_album_area_url, type: "get", params: params, needCookie: true};
                            return {"request": JSON.stringify(requestData), timeSign: currentTime}
                        },
                        process: function (json) {
                            var ret = [],
                                self = this,
                                options = self.options,
                                itemData = null;
                            var data = null;
                            if (json == null) {
                                EpgWeb.Plugin.showTips({content: "获取接口数据失败", type: "error"});
                                return [];
                            }
                            if (json.code === "A00000") {
                                data = $.isArray(json) ? json : json.data;
                            }
                            if (!data) {
                                return [];
                            }
                            var currentTime = new Date().getTime();
                            $.map(data, function (item) {
                                if (item["qipuId"] == null || item["qipuId"] == 0) {
                                    return true;
                                }
                                itemData = {};
                                itemData[options.valueKey] = item["qipuId"];
                                itemData[options.labelKey] = item["displayName"];
                                itemData["channelName"] = item["channelName"];
                                itemData["copyrightBeginTime"] = item["copyright"] ? item["copyright"][0].copyrightBeginTime : null;
                                itemData["copyrightEndTime"] = item["copyright"] ? item["copyright"][0].copyrightEndTime : null;
                                itemData["isPurchase"] = item["isPurchase"];
                                itemData["pagePublishStatus"] = item["pagePublishStatus"];
                                itemData["entityId"] = item["entityId"];
                                itemData["totalNum"] = item["totalNumberOfEpisodes"]
                                itemData.hintMsgObj = item.hintMsgObj;
                                itemData["pageUrl"] = item["pageUrl"];
                                ret.push(itemData);
                            });
                            return ret;
                        },
                        template: function (item) {
                            return "";
                           // return Carousel.Formatter.getTemplate(item)
                        },
                        header: Carousel.Util.template.albumSuggest(Carousel.Config.Header.albumSuggest)
                    }
                }
            },

            fillRuleView: function (element) {
                var self = this;
                Carousel.Config.ruleSelectElement = element;
                if (element.totalNum > 0) {
                    $("input[name=totalNum]").val(element.totalNum);
                }

                $("#loadLegoMessage").dialog("open");
                Carousel.Util.queryTotalNum(element.entityId, function () {
                    $("#loadLegoMessage").dialog("close");
                    if (element.totalNum == 0) {
                        element.totalNum = parseInt($("input[name=actualNum]").val(), 10);
                        $("input[name=totalNum]").val($("input[name=actualNum]").val());
                    }
                    self.checkTotalAndActual();
                    console.log("填充数据完成");
                });
            },

            checkTotalAndActual: function () {
                var actualNum = $("input[name=actualNum]").val();
                var totalNum = $("input[name=totalNum]").val();
                $("input[name=check_follow]").removeAttr("checked");
                $("input[name=check_repeat]").removeAttr("checked");
                $("input[name=check_follow]").attr("disabled", "disabled");
                $("input[name=check_repeat]").attr("disabled", "disabled");
                if (actualNum === "") {
                    EpgWeb.Plugin.showTips({content: "奇谱没有相应数据", type: "error"});
                    return;
                }
                if (actualNum == totalNum) {
                    $("input[name=check_repeat]").removeAttr("disabled");
                } else {
                    $("input[name=check_follow]").removeAttr("disabled");
                }
            },

            //====================initSuggest end========================================/

            //====================initDialog start========================================/
            dayListUseDlg: function () {
                var self = this;
                self.initLoadLegoDlg();
                self.initDelMessageDlg();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');

            },
            insertUseDlg: function () {
                var self = this;
                self.initLoadLegoDlg();
                self.initBatchResponseDiv();
                self.initQueryMessageDlg();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },
            libraryUseDlg: function () {
                var self = this;
                self.initLoadLegoDlg();
                self.initBatchResponseDiv();
                $(".ui-dialog-titlebar-close").html('<span class="ui-button-icon-primary ui-icon ui-icon-closethick"></span><span class="ui-button-text">close</span>');
            },

            initLoadLegoDlg: function () {
                $("#loadLegoMessage").dialog({
                    title: "数据加载",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                });
            },
            initDelMessageDlg: function () {
                $("#delMessage").dialog({
                    title: "数据删除",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: {
                        "ok": function () {
                            $(this).dialog("close");
                        },
                        "cancel": function () {
                            $(this).dialog("close");
                        }
                    }
                })
            },
            initQueryMessageDlg: function () {
                var self = this;
                $("#queryMessage").dialog({
                    title: "是否继续操作",
                    autoOpen: false,
                    width: 255,
                    minHeight: 150,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false
                })
                $("input[name=btn_nil]").bind("click", function (evt) {
                    $("#queryMessage").dialog("close");
                })
                $("input[name=btn_jump_library]").bind("click", function (evt) {
                    var toUrl = "/epg/carousel_automation_library.html?fatherId=" + self.dao.channelId
                    window.location.href = toUrl;
                })
            },

            initCopyRightDlg: function () {
                $("#notifyCopyRightDlg").dialog({
                    title: "版权到期提醒",
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "继续",
                            click: function () {
                                $(this).dialog("close");
                              //  doHandler(true);
                            }
                        },
                        {
                            text: "中断",
                            click: function () {
                                $(this).dialog("close");
                             //   doHandler(false);
                            }
                        }
                    ]
                });
            },

            initBatchResponseDiv: function () {
                $("#batchResponseDiv").dialog({
                    title: "数据核查汇总",
                    autoOpen: false,
                    width: 440,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    open: function (event) {
                        Carousel.Util.removeDisAble();
                    },
                    buttons: [
                        {
                            text: "继续",
                            click: function () {

                                Carousel.Util.addDisAble();
                                if (Carousel.Config.saveIds == null) {
                                    Carousel.Util.removeDisAble();
                                } else {
                                    Carousel.Util.batchAddByBindModel();
                                }
                                $(this).dialog("close");
                            }
                        },
                        {
                            text: "中断",
                            click: function () {
                                $(this).dialog("close");
                            }
                        }
                    ]
                })
            },

            initAdvertDialog:function(){
                $("#advert_dlg").dialog({
                    title: "编辑广告点",
                    autoOpen: false,
                    width: 440,
                    modal: true,
                    dialogClass: 'alert',
                    resizable: false,
                    buttons: [
                        {
                            text: "确定",
                            click: function () {
                                if(Carousel.Dao.cfgName.ad_selected > 0){
                                    Carousel.Dao.postModifyAdvert({id:Carousel.Dao.cfgName.ad_selected,  enable:   parseInt( $("input[name=advertEnable]:checked").val()) }, function (data) {
                                        Carousel.Util.reloadHandler(data);
                                    })
                                }
                                $(this).dialog("close");
                            }
                        },
                        {
                            text: "取消",
                            click: function () {
                                Carousel.Dao.cfgName.ad_selected = 0;
                                $(this).dialog("close");
                            }
                        }
                    ]
                });
            },

            //====================================================//
            initWeekToolBar: function () {
                var self = this;
                Carousel.Util.WeekManager = EpgWeb.Util.createWeekManager($("#dayRange div label"));
                var weekRangeLabel = $("#weekRange label");
                $(weekRangeLabel[0]).bind("click", function () {
                    Carousel.Util.WeekManager.preWeek();
                });
                $(weekRangeLabel[1]).bind("click", function () {
                    self.updateTableByDate(Carousel.Util.WeekManager.quickToCurrentWeek());
                })
                $(weekRangeLabel[2]).bind("click", function () {
                    Carousel.Util.WeekManager.nextWeek()
                })
                $("button.left").bind("click", function () {
                    Carousel.Util.WeekManager.preWeek()
                })

                $("button.right").bind("click", function () {
                    Carousel.Util.WeekManager.nextWeek()
                })

                $("#dayRange div label").bind("click", function (event) {
                    var aChild = event.currentTarget;
                    $(aChild).parent().find("label").removeClass("selected");
                    $(aChild).addClass("selected");
                    self.updateTableByDate(aChild.getAttribute("query-date"))
                })
                self.updateTableByDate(Carousel.Util.WeekManager.quickToCurrentWeek());
            },
            updateTableByDate: function (lDateFormat) {
                var self = this;
                self.config.dateTime = lDateFormat;
                self.$grid.setGridParam({page: 1, url: EpgWeb.urlConfig.programList, loadtext: '加载中...',
                    datatype: "json",
                    loadui: "block", postData: self.getListParam()}).trigger("reloadGrid");
            }
            //====================================================//
        })
    }
);